package com.ljx.Daoyu;

import java.util.Arrays;

/**
 * @author 李加喜
 * @Package com.ljx.List
 * @date 2021-11-07 22:42
 */
// 连在一起的称之为岛屿
public class Daoyu2 {
    public static void main(String[] args) {
        Daoyu2 daoyu2 = new Daoyu2();
        int[][] grid={{1,1,1,1,1,1,1,0},{1,0,0,0,0,1,1,0},{1,0,1,0,1,1,1,0},{1,0,0,0,0,1,0,1},{1,1,1,1,1,1,1,0}};
        daoyu2.closedIsland(grid);
    }
    public int closedIsland(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int j = 0; j < n; j++) {
            // 把靠上边的岛屿淹掉
            dfs(grid, 0, j);
//            System.out.println(Arrays.toString(grid[1]));
            // 把靠下边的岛屿淹掉
            dfs(grid, m - 1, j);
//            System.out.println(Arrays.toString(grid[1]));
        }
        System.out.println(Arrays.deepToString(grid));
        for (int i = 0; i < m; i++) {
            // 把靠左边的岛屿淹掉
            dfs(grid, i, 0);
            // 把靠右边的岛屿淹掉
            dfs(grid, i, n - 1);
        }
        System.out.println(Arrays.deepToString(grid));
//        // 遍历 grid，剩下的岛屿都是封闭岛屿
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 2; j < n; j++) {
                if (grid[i][j] == 0) {
                    res++;
                    System.out.println("行"+i+"列"+j+ Arrays.toString(grid[i]));
                    dfs(grid, i, j);
                }
            }
        }
        System.out.println(Arrays.deepToString(grid));

        return 1;
    }

    // 从 (i, j) 开始，将与之相邻的陆地都变成海水
    public void dfs(int[][] grid, int i, int j) {
//        int[][] grid={
//        {1,1,1,1,1,1,1,0},
//        {1,0,0,0,0,1,1,0},
//        {1,0,1,0,1,1,1,0},
//        {1,0,0,0,0,1,0,1},
//        {1,1,1,1,1,1,1,0}
//        };
        int m = grid.length, n = grid[0].length;
        if (i < 0 || j < 0 || i >= m || j >= n) {
            return;
        }
        if (grid[i][j] == 1) {
            // 已经是海水了
            return;
        }
        // 将 (i, j) 变成海水
        grid[i][j] = 1;
        // 淹没上下左右的陆地
        dfs(grid, i + 1, j);
        dfs(grid, i, j + 1);
        dfs(grid, i - 1, j);
        dfs(grid, i, j - 1);
    }
}
